import React from 'react'
import { Button, Icon, Badge, Affix, Modal, Form, Alert, Select, AutoComplete, message, Tooltip } from 'antd'
import { messages, queryCurrencyPrecision } from "share/common";
const FormItem = Form.Item;
const Option = Select.Option;
import 'styles/setting/wait-for-billing/search-billing-detail.scss'
import ExportModal from "components/template/export-modal/export-modal";
import BillingService from 'containers/financial-management/wait-for-billing/wait-for-billing.service'
import {connect} from "react-redux";
import constants from "share/constants";
import menuRoute from "routes/menuRoute";
import AddressPicker from 'containers/financial-management/wait-for-billing/new-billing/address-picker'
import ResizeTable from 'components/resize-table'

class SearchBillingDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {
          title: messages('common.sequence')/*序号*/,
          dataIndex: 'index',
          render: (value, record, index) => (this.state.page * 10 + index + 1)
        },
        {title: messages('financial-management.key515'/*法人*/), dataIndex: 'expenseLegalEntityName'},
        {title: messages('common.user.id')/*工号*/, dataIndex: 'employeeId'},
        {title: messages('financial-management.key516'/*姓名*/), dataIndex: 'employeeName'},
        {title: messages('financial-management.key167'/*报销单号*/), dataIndex: 'businessCode'},
        {
          title: messages('common.happened.date')/*发生日期*/,
          dataIndex: 'createdDate',
          render: createdDate => new Date(createdDate).format('yyyy-MM-dd')
        },
        {title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode'},
        {
          title: messages('common.amount')/*金额*/,
          dataIndex: 'orderAmount',
          render: (orderAmount, record) => this.filterMoney(orderAmount, queryCurrencyPrecision(record.currencyCode))
        },
        // {
        //   title: messages('financial-management.key517'/*支付方式*/), dataIndex: 'paymentType', render: (value) => {
        //     let result = (value === 1001 ? messages('financial-management.key411'/*个人垫付*/) : messages('financial-management.key412'/*公司垫付*/));
        //     return result;
        //   }
        // },
        {title: messages('budget-setting.key85'/*费用类型*/), dataIndex: 'invoiceName', render: (value) => {
          return (<Tooltip title={value}>{value}</Tooltip>)
        }},
        {
          title: messages('financial-management.key518'/*报销单状态*/),
          dataIndex: 'expenseReportStatus',
          render: (value) => {
            return (
              <Badge text={constants.getTextByValue(String(value), 'documentStatus')}
                     status={constants.getTextByValue(String(value), 'documentStatus', 'state')}/>
            )
          }
        },
        {title: '复审日期', dataIndex: 'auditApprovalDate', render: auditApprovalDate => new Date(auditApprovalDate).format('yyyy-MM-dd')},

      ],
      legalEntityOid: props.params.legalEntityOid,
      searchParams: JSON.stringify(this.props.searchBilling) !== "{}" ? this.props.searchBilling : this.props.location.state.params,
      date: [],
      pagination: {
        total: 0,
      },
      page: 0,
      pageSize: 10,
      tableLoading: false,
      showAdressPicker: false,
      showConfirmModal: false,
      okLoading: false,
      ruleTypeOptions: [],
      defaultAddressInfo: {},
      invoiceTitle: [],
      dataSource: [],
      billingType: JSON.stringify(props.billingType) !== "{}" ? props.billingType : props.params.billingType,
      taxpayerNumber: null,
      expenseLETaxPayerNumber: ''
    };
    this.searchNewBilling = menuRoute.getRouteItem('search-new-billing');
    this.waitForBillingRouter = menuRoute.getRouteItem('wait-for-billing-list');
  }

  componentWillMount() {
    this.getList();
    this.getInvoiceTitle();
  };

  getList = (isChangePaper) => {
    this.setState({tableLoading: true});
    isChangePaper && this.setState({page: 0});
    const {legalEntityOid, searchParams, page, pageSize} = this.state;
    let searchParam = JSON.parse(JSON.stringify(searchParams));
    searchParam.expenseSearchLegalEntityOIDs = [legalEntityOid];
    searchParam.page = isChangePaper ? 0 : page;
    searchParam.size = pageSize;
    BillingService.getDetailDate(searchParam.vendor, searchParam).then((res) => {
      res.data.rows.map((item, index) => {
        item.index = index + pageSize * page + 1;
        return item;
      });
      this.setState({
        tableLoading: false,
        date: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          onChange: this.onChangePager,
          current: (isChangePaper ? 0 : page) + 1
        },
        expenseLETaxPayerNumber: res.data.rows[0].expenseLETaxPayerNumber
      })
    });
  };

  //获得抬头信息
  getInvoiceTitle = () => {
    let params = {
      companyOid: this.props.company.companyOID
    };
    BillingService.getInvoiceTitle(this.state.billingType, params).then(res => {
      if (res.data) {
        this.setState({invoiceTitle: res.data})
      }
    });
  };

  //获取供应商发票类型
  getVendorInvoiceType = () => {
    const { billingType, taxpayerNumber } = this.state;
    BillingService.getVendorInvoiceType(billingType, taxpayerNumber).then(res => {
      if (res.data && res.data.length > 0) {
        if (res.data.filter(item => !this.switchReceiving(item.type)).length > 0) {
          this.getDefaultAddress();
        }
        this.setState({ ruleTypeOptions: res.data }, () => {
          this.props.form.setFieldsValue({ invoiceApplyType: res.data[0].type });
        });
      }
    }).catch(e => {
      this.setState({ ruleTypeOptions: [] }, () => {
        this.props.form.setFieldsValue({ invoiceApplyType: undefined });
      });
      message.error(e.response.data.message);
    })
  };

  //根据发票类型状态切换收件信息
  switchReceiving = (type) => {
    let email = ['ELECTRONICORDINARY'];
    return (type && ~email.indexOf(type));
  };

  //获得默认地址
  getDefaultAddress = () => {
    BillingService.getDefaultAddress().then(res => {
      this.setState({defaultAddressInfo: res.data})
    })
  };

  //开票
  openSearchTicket = () => {
    this.setState({showConfirmModal: true},() => {
      const { invoiceTitle, expenseLETaxPayerNumber } = this.state;
      let temp = invoiceTitle.find(item => item.tax_registration_number === expenseLETaxPayerNumber) || {}
      this.handleChangeInvoice(temp.invoice_title);
    });
  };

  //确认开票
  handleOpenTicket = () => {
    let {searchParams, invoiceTitle, defaultAddressInfo, legalEntityOid} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let temp = {};
        if (!this.switchReceiving(values.invoiceApplyType) && (!defaultAddressInfo || !defaultAddressInfo.billingContactOID)) {
          message.warn(messages('financial-management.key460'/*请选择收货地址*/));
          return;
        }
        if (!this.switchReceiving(values.invoiceApplyType)) {
          temp.billingContactOID = defaultAddressInfo.billingContactOID
        }
        temp.qid = invoiceTitle.filter(item => item.invoice_title === values.title)[0].id;
        temp.taxpayerNumber = invoiceTitle.filter(item => item.invoice_title === values.title)[0].tax_registration_number;
        temp.currencySymbol = constants.CurrencyCode[this.props.companyConfiguration.currencyCode];
        if (this.state.billingType !== 'CLOUD_HELIOS_HOTEL' && searchParams.company) {
          temp.vendorAccountId = searchParams.company.vendorAccountId;
          temp.vendorAccountName = searchParams.company.vendorAccountName;
        }
        Object.assign(searchParams, {expenseSearchLegalEntityOIDs: [legalEntityOid]});
        let params = { ...searchParams, ...values, ...temp };
        this.openTicket(params)
      }
    })
  };

  //取消确认开票
  onConfirmCancel = () => {
    this.setState({showConfirmModal: false})
  };

  //开票
  openTicket = (params) => {
    this.setState({okLoading: true});
    BillingService.applyForReceiptedInvoice(this.state.billingType, params).then(res => {
      this.setState({okLoading: false});
      if (res.status === 200) {
        message.success(messages('financial-management.key521'/*申请成功!*/));
        this.onConfirmCancel();
        this.context.router.push(this.waitForBillingRouter.url.replace(':billingType', this.state.billingType))
      }
    }).catch(e => {
      this.setState({okLoading: false});
      message.error(messages('financial-management.key522'/*申请失败!*/))
    })
  };

  //选择更多收件地址
  showAdressPicker = () => {
    this.setState({showAdressPicker: true});
  };

  //取消地址选择
  AddressPickerCancel = () => {
    this.setState({showAdressPicker: false});
  };

  //确认选择地址
  handleChooseAddress = (value) => {
    this.setState({defaultAddressInfo: value})
  };

  //根据发票类型状态切换收件信息
  switchReceiving = (type) => {
    let email = ['ELECTRONICORDINARY'];
    return (type && ~email.indexOf(type));
  };

  emailHandleChange = (value) => {
    this.setState({
      dataSource: !value || value.indexOf('@') >= 0 ? [] : [
        `${value}@${this.props.user.email && ~this.props.user.email.indexOf('@') ? this.props.user.email.split('@')[1] : ''}`,
        `${value}@163.com`,
        `${value}@126.com`,
        `${value}@qq.com`,
        `${value}@sina.com`,
      ],
    });
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList(false);
      })
  };

  goBack = () => {
    this.context.router.push(this.searchNewBilling.url.replace(':billingType', this.state.billingType));
  };

  handleChangeInvoice = value => {
    const { invoiceTitle } = this.state;
    let temp = invoiceTitle.find(item => item.invoice_title === value) || {};
    this.setState({ taxpayerNumber: temp.tax_registration_number },() => {
      this.getVendorInvoiceType();
    });
  };

  render() {
    const { columns, pagination, date, tableLoading, showConfirmModal, ruleTypeOptions, defaultAddressInfo,
      showAdressPicker, invoiceTitle, dataSource, okLoading, expenseLETaxPayerNumber, taxpayerNumber,searchParams, legalEntityOid} = this.state;
    const {fullName, phone, country, stateProvince, cityRegion, streetLine, billingContactOID} = defaultAddressInfo;
    const {getFieldDecorator} = this.props.form;
    const {user} = this.props;
    let invoiceApplyType = this.props.form.getFieldValue('invoiceApplyType');
    let initValue = invoiceTitle.find(item => item.tax_registration_number === expenseLETaxPayerNumber) || {};
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 14},
    };
    return (
      <div className={"search-billing-detail"}>
        <Affix offsetBottom={0} className="bottom-bar">
          <Button className="back-btn" onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>
        </Affix>
        <div className={"search-title"}>
          {messages('financial-management.key519'/*查询结果*/)}：
          <div style={{float:'right'}}>
          <ExportModal
              type={"btn"}
              btnType="primary"
              exportTitle={'导出数据'}
              exportType="DIDI_NO_RECEIPTED_INVOICE"
              exportCommand={'DIDI_NO_RECEIPTED_INVOICE'}
              exportCondition={{
                "billCheckSearchCommand": {
                 "beginDate": searchParams.startDate || ''
                },
                "vendor": searchParams.vendor || '',
                "legalEntityOID": legalEntityOid || '',
                "vendorAccountId": searchParams.vendorAccountId || ''
                }}/>
          </div>
        </div>
        <Modal visible={showConfirmModal}
               width={800}
               title={messages('financial-management.key514'/*确认开票*/)}
               wrapClassName="search-new-billing"
               className='confirm-receipt-modal'
               onCancel={() => this.setState({showConfirmModal: false})}
               footer={[
                 <Button key="back" onClick={this.onConfirmCancel}>{messages('common.cancel'/*取消*/)}</Button>,
                 <Button key="submit" type="primary" loading={okLoading}
                         onClick={this.handleOpenTicket}>{messages('common.ok'/*确定*/)}</Button>
               ]}>
          <Form>
            <Alert message={messages('financial-management.key645')/*注意！开票抬头如果不是共用一个收件地址或邮箱，请单独进行开票！*/} type="info" showIcon style={{marginBottom: 20}}/>
            <FormItem  {...formItemLayout} label={messages('financial-management.key428'/*开票抬头*/)}>
              {getFieldDecorator("title", {
                rules: [{
                  required: true,
                  message: messages('financial-management.key471'/*请选择发票抬头*/)
                }],
                initialValue: initValue.invoice_title
              })(
                <Select
                  placeholder={messages('financial-management.key472'/*请选择抬头*/)}
                  onChange={this.handleChangeInvoice}
                >
                  {invoiceTitle.map(item => <Option key={item.invoice_title}>{item.invoice_title}</Option>)}
                </Select>
              )}
            </FormItem>
            {
              taxpayerNumber && (
                <FormItem {...formItemLayout} label={messages('financial-management.key433'/*开票类型*/)}>
                  {getFieldDecorator("invoiceApplyType", {
                    rules: [{
                      required: true
                    }]
                  })(
                    <Select>
                      {ruleTypeOptions.map(item => <Option value={item.type} key={item.type}>{item.name}</Option>)}
                    </Select>
                  )}
                </FormItem>
              )
            }
            {this.switchReceiving(invoiceApplyType) ? (
              <FormItem  {...formItemLayout} label={messages('financial-management.key473'/*收件邮箱*/)}>
                {getFieldDecorator("email", {
                  rules: [{
                    required: true,
                    type: 'email',
                    message: `${messages('common.please.enter')}${messages('financial-management.key474'/*正确的收件邮箱*/)}`
                  }],
                  initialValue: user.email
                })(
                  <AutoComplete
                    dataSource={dataSource}
                    style={{width: 310}}
                    onChange={this.emailHandleChange}
                    placeholder={messages('common.please.enter')}
                  />
                )}
              </FormItem>
            ) : (
              <FormItem  {...formItemLayout} label={messages('financial-management.key475'/*收件信息*/)}>
                {getFieldDecorator("address", {
                  rules: [{
                    required: true
                  }],
                  initialValue: `${fullName}  ${phone}  ${country}${stateProvince}${cityRegion}${streetLine}`
                })(
                  <div className='receive-info-content'>
                    {fullName}&nbsp;&nbsp;{phone}&nbsp;&nbsp;{country}{stateProvince}{cityRegion}{streetLine}
                    {defaultAddressInfo && defaultAddressInfo.isDefault &&
                    <div className='default-button'>{messages('financial-management.key476'/*默认地址*/)}</div>}
                    <div className='more-address'
                         onClick={this.showAdressPicker}>{messages('financial-management.key477'/*更多地址*/)}<Icon
                      type="down-circle-o" style={{marginLeft: "5px"}}/></div>
                  </div>
                )}
              </FormItem>
            )}
          </Form>
          {showAdressPicker && <AddressPicker visible={showAdressPicker} onCancel={this.AddressPickerCancel}
                                              moreAdress={value => this.handleChooseAddress(value)} flag={'edit'}
                                              billingContactOID={billingContactOID}/>}
        </Modal>
        <ResizeTable
          style={{marginTop: '20px'}}
          columns={columns}
          dataSource={date}
          size="middle"
          bordered
          rowKey={'index'}
          pagination={pagination}
          loading={tableLoading}
        />
      </div>
    )
  }
}

SearchBillingDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    router: React.PropTypes.object,
    company: state.login.company,
    user: state.login.user,
    companyConfiguration: state.login.companyConfiguration,
    billingType: state.billing.billingType,
    searchBilling: state.billing.searchBilling
  }
}

const WrappedSearchBillingDetail = Form.create()(SearchBillingDetail);
export default connect(mapStateToProps)(WrappedSearchBillingDetail);
